<?php

namespace App\Http\Controllers\AdminApi;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;

class AdminRoleController extends BaseController
{
    public function initialize(Request $request)
    {
        parent::initialize($request);

        $this->modelName = 'VueAdminRole';

        $this->defaultOrder = [
            ['filed' => 'sorting', 'order' => 'ASC'],
            ['filed' => 'created_at', 'order' => 'DESC'],
        ];
    }

    /**
     * Eval data for post data save
     *
     * @param Request $request
     * @return array
     */
    protected function evalData($request)
    {
        $param = $request->all();

        $data = [
            'id' => $param['id'],
            'name' => $param['name'],
            'remark' => $param['remark'],
            'access' => implode(',', $param['access_ids']),
            'sorting' => $param['sorting'],
            'status' => $param['status'],
        ];

        return $data;
    }

    /**
     * 处理列表数据
     */
    protected function handleListData($data)
    {
        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;

        $data = $model->formatDatas($data, ['format_source' => 'backend']);
        $data = list_to_tree($data, 'id', 'parent_id', 'children', 0);

        return $data;
    }

    /**
     * 筛选条件
     */
    protected function getFilterWhere($request)
    {
        $param = $request->all();
        $where = [];
        if (isset($param['name']) && $param['name']) {
            $where[] = ['name', 'like', '%' . trim($param['name']) . '%'];
        }
        if (isset($param['email']) && $param['email']) {
            $where[] = ['email', 'like', '%' . trim($param['email']) . '%'];
        }
        if (isset($param['range_date']) && $param['range_date']) {
            $rangeDate = $param['range_date'];
            $startTime = strtotime($rangeDate[0]);
            $endTime = strtotime($rangeDate[1]);
            $where[] = ['created_at', '>=', $startTime];
            $where[] = ['created_at', '<=', $endTime];
        }

        return $where;
    }
}
